package com.ssd.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.ssd.config.KaptcharConfig;
import com.ssd.entity.User;
import com.ssd.entity.dto.LoginReq;
import com.ssd.entity.vo.LoginResp;
import com.ssd.service.IUserService;
import com.ssd.view.BaseResponse;
import com.ssd.viewmodel.Pager;
import com.ssd.viewmodel.UserWork;
import io.lettuce.core.output.ValueValueListOutput;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author author
 * @since 2024-11-14
 */
@RestController
@RequestMapping("/user")
@Api(tags = "用户表 前端控制器")
public class UserController {
    @Resource
    private IUserService userService;
    @Resource
    private DefaultKaptcha kaptcha;
    @Resource
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 根据用户id查询用户信息
     * @return
     */
    @GetMapping("/{id}")
    @ApiOperation(value = "根据用户id查询用户信息")
    public BaseResponse<User> findById(@ApiParam(value = "用户id") @PathVariable("id") Integer id){
        User user = userService.getById(id);
        if (user != null){
            user.setPassword("******");
        }
        return new BaseResponse<>(user);
    }

    /**
     * 新增用户
     * @param user 新增用户数据
     * @return
     */
    @PostMapping
    @ApiOperation(value = "新增用户")
    public BaseResponse add(@ApiParam(value = "用户数据") @RequestBody User user){
        return userService.add(user);
    }


    /**
     * 根据用户id修改用户数据
     * @param id 用户id
     * @param user 用户实体
     * @return
     */
    @PutMapping("/{id}")
    @ApiOperation(value = "根据用户id修改用户")
    public BaseResponse update(
            @ApiParam(value = "用户id") @PathVariable("id") Long id,
            @ApiParam(value = "用户数据") @RequestBody User user
    ){
        user.setId(id);
        return new BaseResponse(userService.updateById(user));
    }

    /**
     * 根据用户id删除用户信息
     * @param id 用户id
     * @return
     */
    @DeleteMapping("/{id}")
    @ApiOperation(value = "根据用户id删除用户信息")
    public BaseResponse delete(@PathVariable("id") Integer id){
        return new BaseResponse(userService.removeById(id));
    }

    /**
     * 分页查询用户信息
     * @param pageIndex 当前页
     * @param pageSize 每页大小
     * @param userName 用户名称
     * @param roleId 角色id
     * @param isRepair 是否为维修工
     * @return
     */
    @GetMapping("/search")
    @ApiOperation(value = "分页查询用户信息")
    public BaseResponse<Pager<User>> findPage(
            @ApiParam(value = "当前页") @RequestParam(value = "pageIndex", required = false,defaultValue = "1") Integer pageIndex,
            @ApiParam(value = "每页显示条数") @RequestParam(value = "pageSize", required = false,defaultValue = "10") Integer pageSize,
            @ApiParam(value = "用户名称") @RequestParam(value = "userName", required = false,defaultValue = "") String userName,
            @ApiParam(value = "角色id") @RequestParam(value = "roleId", required = false,defaultValue = "0") Integer roleId,
            @ApiParam(value = "是否为维修工" ) @RequestParam(value = "isRepair", required = false) Boolean isRepair

    ){
        return new BaseResponse<>(userService.findPage(pageIndex,pageSize,userName,roleId,isRepair));
    }

    /**
     * 登录
     * @param req
     * @return
     * @throws IOException
     */
    @PostMapping("/login")
    @ApiOperation(value = "后台登录")
    public BaseResponse<LoginResp> login(@RequestBody LoginReq req) throws IOException {
        return userService.login(req);
    }

    /**
     * 生成登录手机验证码
     * @param mobile 手机号
     * @return
     */
    @GetMapping("/code/{mobile}")
    @ApiOperation(value = "生成登录手机验证码")
    public BaseResponse generateCode(@ApiParam(value = "手机号") @PathVariable(value = "mobile") String mobile){
    	userService.sendCode(mobile);
        return new  BaseResponse();
    }

    //TODO 生成图片验证码
    @GetMapping("/imageCode/{clientToken}")
    @ApiOperation(value = "生成图片验证码")
    public void getImageCode(HttpServletRequest request, HttpServletResponse response,@PathVariable("clientToken") String clientToken) throws IOException {
        //创建一个输出流，用于存储生成的验证码图片
        ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
        //生成随机字母+数字(4位)，用于验证码文本
        String createText = kaptcha.createText();
        System.err.println(createText);
        //根据生成的文本构建验证码图片
        BufferedImage challenge = kaptcha.createImage(createText);
        //将验证码图片写入输出流
        ImageIO.write(challenge,"jpg",jpegOutputStream);
        //将输出流转换为字节数组，用于传输
        byte[] captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
        //设置响应内容类型为图片
        response.setContentType("image/jpeg");
        //获取响应输出流，用于向客户端发送图片
        ServletOutputStream responseOutputStream = response.getOutputStream();
        //向响应输出流写入验证码图片数据
        responseOutputStream.write(captchaChallengeAsJpeg);
        //刷新响应输出流，确保数据被发送
        responseOutputStream.flush();
        //关闭响应输出流
        responseOutputStream.close();
        //将验证码文本存入redis，设置过期时间为2分钟
        redisTemplate.boundValueOps(clientToken).set(createText,120, TimeUnit.SECONDS);
    }


    /**
     * 获取运营员数量
     * @return
     */
    @GetMapping("/operatorCount")
    @ApiOperation(value = "获取运营员数量")
    public BaseResponse<Integer> getOperatorCount(){
        return new BaseResponse<>(userService.lambdaQuery().eq(User::getRoleCode,"1002").count());
    }
    /**
     * 获取维修员数量
     * @return
     */
    @GetMapping("/repairerCount")
    @ApiOperation(value = "获取运营员数量")
    public BaseResponse<Integer> getRepairerCount(){
        return new BaseResponse<>(userService.lambdaQuery().eq(User::getRoleCode,"1003").count());
    }

    /**
     * 获取某区域下所有运营人员
     * @param regionId 区域id
     * @return
     */
    @ApiOperation(value = "获取某区域下所有运营人员")
    @GetMapping("/operators/{regionId}")
    public BaseResponse<List<User>> getOperatorList(@ApiParam(value = "区域id") @PathVariable("regionId") Long regionId){
        return userService.getOperatorList(regionId);
    }

    /**
     * 获取某区域下所有维修人员
     * @param regionId 区域id
     * @return
     */
    @ApiOperation(value = "获取某区域下所有维修人员")
    @GetMapping("/repairers/{regionId}")
    public BaseResponse<List<User>> getRepairerList(@ApiParam(value = "区域id") @PathVariable("regionId") Long regionId){
    	return userService.getRepairerList(regionId);
    }

    /**
     * 通过售货机编号获取同区域下所有运营员
     * @param innerCode 售货机编号
     * @return
     */
    @ApiOperation(value = "通过售货机编号获取同区域下所有运营员")
    @GetMapping("/operatorList/{innerCode}")
    public BaseResponse<List<User>> getOperatorListByInnerCode(@ApiParam(value = "售货机编号") @PathVariable("innerCode") String innerCode){
        //1.远程调用售货机服务，获取区域id
        //TODO
        return userService.getOperatorList(1L);
    }

    /**
     * 通过售货机编号获取同区域下所有维修员
     * @param innerCode 售货机编号
     * @return
     */
    @ApiOperation(value = "通过售货机编号获取同区域下所有维修员")
    @GetMapping("/repairerList/{innerCode}")
    public BaseResponse<List<User>> getRepairerListByInnerCode(@ApiParam(value = "售货机编号") @PathVariable("innerCode") String innerCode){
        //1.远程调用售货机服务，获取区域id
        //TODO
        return userService.getRepairerList(1L);
    }


    /**
     * 获取某区域下维修员/运营员
     * @param regionId 区域id
     * @param isRepair 是否为维修工
     * @return
     */
    @ApiOperation(value = "获取某区域下维修员/运营员")
    @GetMapping("/countByRegion/{regionId}/{isRepair}")
    public BaseResponse<Integer> getCountByRegion(@ApiParam(value = "区域id") @PathVariable("regionId") Long regionId,@ApiParam(value = "是否维修员") @PathVariable("isRepair") Boolean isRepair){
        return new BaseResponse<>(userService.lambdaQuery()
                .eq(User::getRegionId,regionId)
                .eq(User::getRoleCode,isRepair?"1003":"1002")
                .count());
    }

    /**
     * 搜索用户工作量列表
     * @param pageIndex 当前页
     * @param pageSize 每页大小
     * @param userName 用户名
     * @param roleCode 角色code
     * @return
     */
    @GetMapping("searchUserWork")
    @ApiOperation(value = "搜索用户工作量列表")
    public BaseResponse<Pager<UserWork>> searchUserWork(
            @RequestParam(value = "pageIndex",required = false,defaultValue = "1") long pageIndex,
            @RequestParam(value = "pageSize",required = false,defaultValue = "10") long pageSize,
            @RequestParam(value = "userName",required = false,defaultValue = "") String userName,
            @RequestParam(value = "roleId",required = false) String roleCode
    ){
        return userService.searchUserWork(pageIndex,pageSize,userName,roleCode);
    }
}
